# -*- coding: utf-8 -*-
"""
小说编辑器组件
"""

from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTabWidget,
                             QTextEdit, QListWidget, QPushButton, QLineEdit,
                             QLabel, QSplitter, QInputDialog, QMessageBox,
                             QListWidgetItem, QMenu)
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QFont, QTextCursor

from ..models.novel import Novel
from ..models.chapter import Chapter


class ChapterEditor(QTextEdit):
    """章节编辑器"""
    
    content_changed = Signal()
    
    def __init__(self, chapter: Chapter = None):
        super().__init__()
        self.chapter = chapter
        
        # 设置字体
        font = QFont("Microsoft YaHei", 12)
        self.setFont(font)
        
        # 连接信号
        self.textChanged.connect(self.on_text_changed)
        
        if self.chapter:
            self.setPlainText(self.chapter.content)
    
    def set_chapter(self, chapter: Chapter):
        """设置章节"""
        self.chapter = chapter
        if chapter:
            self.setPlainText(chapter.content)
        else:
            self.clear()
    
    def on_text_changed(self):
        """文本改变时更新章节内容"""
        if self.chapter:
            self.chapter.update_content(self.toPlainText())
        self.content_changed.emit()
    
    def insert_text(self, text: str):
        """插入文本"""
        cursor = self.textCursor()
        cursor.insertText(text)
        self.setTextCursor(cursor) 


class NovelEditor(QWidget):
    """小说编辑器主组件"""
    
    content_changed = Signal()
    
    def __init__(self, novel: Novel):
        super().__init__()
        self.novel = novel
        self.current_chapter = None
        
        self.init_ui()
        self.load_chapters()
    
    def init_ui(self):
        """初始化用户界面"""
        layout = QVBoxLayout(self)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        layout.addWidget(splitter)
        
        # 左侧：章节列表
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        
        # 章节列表标题和按钮
        title_layout = QHBoxLayout()
        title_layout.addWidget(QLabel("章节列表"))
        title_layout.addStretch()
        
        add_chapter_btn = QPushButton("添加章节")
        add_chapter_btn.clicked.connect(self.add_chapter)
        title_layout.addWidget(add_chapter_btn)
        
        left_layout.addLayout(title_layout)
        
        # 章节列表
        self.chapter_list = QListWidget()
        self.chapter_list.itemClicked.connect(self.on_chapter_selected)
        self.chapter_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.chapter_list.customContextMenuRequested.connect(self.show_chapter_context_menu)
        left_layout.addWidget(self.chapter_list)
        
        splitter.addWidget(left_widget)
        
        # 右侧：章节编辑器
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)
        
        # 章节标题编辑
        title_layout = QHBoxLayout()
        title_layout.addWidget(QLabel("章节标题:"))
        
        self.chapter_title_edit = QLineEdit()
        self.chapter_title_edit.textChanged.connect(self.on_title_changed)
        title_layout.addWidget(self.chapter_title_edit)
        
        right_layout.addLayout(title_layout)
        
        # 章节内容编辑器
        self.chapter_editor = ChapterEditor()
        self.chapter_editor.content_changed.connect(self.on_content_changed)
        right_layout.addWidget(self.chapter_editor)
        
        # 字数统计
        self.word_count_label = QLabel("字数: 0")
        right_layout.addWidget(self.word_count_label)
        
        splitter.addWidget(right_widget)
        
        # 设置分割器比例
        splitter.setSizes([200, 600])
    
    def set_novel(self, novel: Novel):
        """设置小说"""
        self.novel = novel
        self.current_chapter = None
        self.load_chapters()
        self.chapter_editor.set_chapter(None)
        self.chapter_title_edit.clear()
        self.update_word_count()
    
    def load_chapters(self):
        """加载章节列表"""
        self.chapter_list.clear()
        if not self.novel:
            return
        
        for chapter in sorted(self.novel.chapters, key=lambda x: x.order):
            item = QListWidgetItem(f"{chapter.order}. {chapter.title}")
            item.setData(Qt.UserRole, chapter.id)
            self.chapter_list.addItem(item)
    
    def add_chapter(self):
        """添加章节"""
        title, ok = QInputDialog.getText(self, "添加章节", "请输入章节标题:")
        if ok and title.strip():
            chapter = self.novel.add_chapter(title.strip())
            self.load_chapters()
            
            # 选中新添加的章节
            for i in range(self.chapter_list.count()):
                item = self.chapter_list.item(i)
                if item.data(Qt.UserRole) == chapter.id:
                    self.chapter_list.setCurrentItem(item)
                    self.on_chapter_selected(item)
                    break
    
    def on_chapter_selected(self, item: QListWidgetItem):
        """章节选择事件"""
        chapter_id = item.data(Qt.UserRole)
        
        # 查找对应的章节
        chapter = None
        for ch in self.novel.chapters:
            if ch.id == chapter_id:
                chapter = ch
                break
        
        if chapter:
            self.current_chapter = chapter
            self.chapter_editor.set_chapter(chapter)
            self.chapter_title_edit.setText(chapter.title)
            self.update_word_count()
    
    def on_title_changed(self):
        """章节标题改变事件"""
        if self.current_chapter:
            new_title = self.chapter_title_edit.text()
            self.current_chapter.update_title(new_title)
            
            # 更新列表中的标题
            for i in range(self.chapter_list.count()):
                item = self.chapter_list.item(i)
                if item.data(Qt.UserRole) == self.current_chapter.id:
                    item.setText(f"{self.current_chapter.order}. {new_title}")
                    break
    
    def on_content_changed(self):
        """内容改变事件"""
        self.update_word_count()
        self.content_changed.emit()
    
    def update_word_count(self):
        """更新字数统计"""
        if self.current_chapter:
            word_count = self.current_chapter.get_word_count()
            self.word_count_label.setText(f"字数: {word_count}")
        else:
            self.word_count_label.setText("字数: 0")
    
    def show_chapter_context_menu(self, pos):
        """显示章节右键菜单"""
        item = self.chapter_list.itemAt(pos)
        if item:
            menu = QMenu(self)
            
            rename_action = menu.addAction("重命名")
            rename_action.triggered.connect(lambda: self.rename_chapter(item))
            
            delete_action = menu.addAction("删除")
            delete_action.triggered.connect(lambda: self.remove_chapter(item.data(Qt.UserRole)))
            
            menu.exec(self.chapter_list.mapToGlobal(pos))
    
    def rename_chapter(self, item: QListWidgetItem):
        """重命名章节"""
        chapter_id = item.data(Qt.UserRole)
        
        # 查找对应的章节
        chapter = None
        for ch in self.novel.chapters:
            if ch.id == chapter_id:
                chapter = ch
                break
        
        if chapter:
            new_title, ok = QInputDialog.getText(self, "重命名章节", 
                                               "请输入新的章节标题:", 
                                               text=chapter.title)
            if ok and new_title.strip():
                chapter.update_title(new_title.strip())
                item.setText(f"{chapter.order}. {new_title.strip()}")
                
                if self.current_chapter and self.current_chapter.id == chapter_id:
                    self.chapter_title_edit.setText(new_title.strip())
    
    def remove_chapter(self, chapter_id: str):
        """删除章节"""
        reply = QMessageBox.question(self, "确认删除", 
                                   "确定要删除这个章节吗？此操作不可撤销。",
                                   QMessageBox.Yes | QMessageBox.No,
                                   QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            if self.novel.remove_chapter(chapter_id):
                self.load_chapters()
                if self.current_chapter and self.current_chapter.id == chapter_id:
                    self.current_chapter = None
                    self.chapter_editor.set_chapter(None)
                    self.chapter_title_edit.clear()
                    self.update_word_count()
    
    def insert_content(self, content: str):
        """插入内容到当前章节"""
        if self.current_chapter:
            self.chapter_editor.insert_text(content)
        else:
            QMessageBox.information(self, "提示", "请先选择一个章节来插入内容")
    
    def undo(self):
        """撤销"""
        if self.chapter_editor:
            self.chapter_editor.undo()
    
    def redo(self):
        """重做"""
        if self.chapter_editor:
            self.chapter_editor.redo() 